package com.campus.gateway;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.core.annotation.Order;
import reactor.core.publisher.Mono;

@SpringBootApplication
public class GateWayServiceApplication {

    private static final Logger logger = LoggerFactory.getLogger(GateWayServiceApplication.class);

    public static void main(String[] args) {
        SpringApplication.run(GateWayServiceApplication.class, args);
    }

    @Bean
    @Order(-1) // 设置过滤器优先级
    public GlobalFilter loggingFilter() {
        return (exchange, chain) -> {
            // 获取请求信息
            String requestPath = exchange.getRequest().getURI().getPath();
            String method = exchange.getRequest().getMethod().name();

            logger.info("Incoming request - Path: {}, Method: {}", requestPath, method);

            // 继续处理请求，并记录响应信息
            return chain.filter(exchange).then(Mono.fromRunnable(() -> {
                int statusCode = exchange.getResponse().getStatusCode() != null
                        ? exchange.getResponse().getStatusCode().value()
                        : 0;
                logger.info("Response status - Path: {}, Status Code: {}", requestPath, statusCode);
            }));
        };
    }
}
